<?php
/**
 * Clean input arrays
 *
 * @param array $inputArr
 * @return array cleaned up input
 */
function cleanInput($inputArr) {
	$cleanArr = array();
	$myts =& MyTextSanitizer::getInstance();
	foreach ($inputArr as $key => $value) {
		$cleanArr[$key] = $myts->stripSlashesGPC($myts->censorString($value));
	}
	return $cleanArr;
}

/**
 * verifies specified keys exist in array.
 *
 * @param array $inputArr (array to check for keys)
 * @param array $keylist (array of key names to verify)
 * @return array of keys not found
 */

function verifyKeys($inputArr, $keylist) {
	$missingKeys = null;
	foreach ($keylist as $key) {
		if (empty($inputArr[$key])) {
			$missingKeys[] = $key;
		}
	}
	return $missingKeys;
}

/**
 * returns 0 if data is ok. Returns 1 if user has selected no attendence days
 * returns 2 if user has selected a workshop but not the attendence day for that workshop
 *
 * @param array $userArr (user data)
 * @return 
 */

function validateUserDays($form, $dateNames) {

	// make sure at least one day of attendence is selected
	// save date attendence
	$attend_days = '';
	foreach (array_keys($form) as $key) {
		if (preg_match("/^(date)/",$key) > 0) {
			if ($form[$key] == 'Yes') {
				$attend_days .= $dateNames[intval(substr($key,4))] . " ";
			}
		}
	}

	if ($attend_days == '') {
		return 1;
	}

	$extraDates = getExtraDates($form['conf_id']);
	
	// verify that if a workshop is selected that the corresponding
	// attending date is checked
	foreach (array_keys($form) as $key) {
		if (preg_match("/^(workshop)/",$key) > 0) {
			$e_id = intval($form[$key]);
			if ($e_id > 0) {
				if (stripos($attend_days,$extraDates[$e_id]) === FALSE) {
					return 2;
				}
			}
		}
	}
	
	// otherwise return 0
	return 0;
}



/**
 * moves form data about a user into aan rray
 *
 * @param array $form data from form, already cleaned
 * @param int $user_id
 * @param array $confData conference data
 * @param array $dateNames human readable date names
 * @param array $extraNames human readable extra names
 * @return array of user data
 */

function userData($form, $user_id, $confData, $dateNames, $extraNames) {
	$user_id = intval($user_id);

	$user['user_id'] = $user_id;
	$user['first_name'] = $form['fname'];
	$user['last_name'] = $form['lname'];
	$user['member_num'] = $form['member'];
	$user['email'] = $form['email'];

	// save date attendence
	$user['attend_desc'] = '';
	for ($i = 0; $i <= intval($confData['day_count']); $i++) {
		if ($form['date'.$i] == 'Yes') {
			$user['day'][$i] = 1;
			$user['attend_desc'] .= $dateNames[$i] . '<br />';
		} else {
			$user['day'][$i] = 0;
		}
	}

	// save selected workshops and extras
	$user['extras_desc'] = '';
	$e_count = 0;
	foreach (array_keys($form) as $key) {
		if (preg_match("/^(workshop)|(extra)/",$key) > 0) {
			$e_id = intval($form[$key]);
			if ($e_id > 0) {
				$user['extra'][$e_count++] = $e_id;
				$user['extras_desc'] .= $extraNames[$e_id] . '<br />';
			}
		}
	}
	
	$user['cost'] = calcUserCost($user,$confData);
	$user['cost_disp'] = '$' . money_format('%.2n',$user['cost']);

	return $user;
}

/**
 * calculates each user's cost
 *
 * @param array $user has all the user data to calc costs
 * @param array $confData has all the prices used to calc costs
 * @return array with user data fields saved to new fields,
 */

 function calcUserCost($thisUser, $confData) {
 	global $xoopsDB;

	// find cost per person per day
	$right_now = mktime();
	if ($right_now <= strtotime($confData['early_cutoff'])) {
		$day_cost = floatval($confData['early_cost']);
	} else {		
		$day_cost = floatval($confData['late_cost']);
	}	

	// fetch day costs for coupons
	$cHdl =& $xoopsDB->query("SELECT * " .
	                         " FROM " . $xoopsDB->prefix("confreg_coupons") .
							 " WHERE conf_id=" . $confData['conf_id']);

	while ($aCoup = $xoopsDB->fetchArray($cHdl)) {
			$ccode = strtolower($aCoup['code']);
			$coupCost[$ccode] = floatval($aCoup['fixed_cost']);
			$coupDiscount[$ccode] = floatval($aCoup['discount'])/100;
	}

	// fetch the costs for extra items from the database
	$wHdl =& $xoopsDB->query("SELECT extra_id, cost" . 
	                         " FROM " . $xoopsDB->prefix("confreg_extras") .
							 " WHERE conf_id=" . $confData['conf_id']);
	while ($aExtra = $xoopsDB->fetchArray($wHdl)) {
			$eCost[$aExtra['extra_id']] = floatval($aExtra['cost']);
	}

	// check coupon codes
	if (isset($thisUser['member_num'])) {
		$membernum = strtolower($thisUser['member_num']);
		if ($coupCost[$membernum] > 0) {
			$day_cost = $coupCost[$membernum];
		} elseif ($coupDiscount[$membernum] > 0) {
			$day_cost = $day_cost - ($day_cost * $coupDiscount[$membernum]);
		}
	}

	$thisCost = 0;
	// loop through days attending
	foreach ($thisUser['day'] as $thisDay) {
		if ($thisDay == 1) {
			$thisCost += $day_cost;
		}
	}

	// add costs for extras
	foreach ($thisUser['extra'] as $e_id) {
		if ($eCost[$e_id] > 0) {
			$thisCost +=  $eCost[$e_id];
		}
	}

	return $thisCost;		
}

/**
 * calculates total cost of all users
 *
 * @param array $user has all the user data to calc costs
 * @return total cost
 */

function calcTotalCost($user) {
	global $xoopsDB;

	$total_cost = 0;
	// loop through each user
	foreach ($user as $thisUser) {
		$total_cost += $thisUser['cost'];
	}
	return $total_cost;
}

/**
 * returns the still available workshops for a given
 * day/time. 
 *
 * @param integer $confid (conference id)
 * @param date $starttime => string in format YYYY-MM-DD
 * @param array $users => user data filled in so far
 * @return array of open workshops
 */

function getWorkshops($conf_id, $starttime, $users) {
	global $xoopsDB;

	// get counts for current user reservations not yet in database
	// loop through each user
	if (isset($users)) { 
 		foreach ($users as $thisUser) {
 			// loop through each extra reservation
 			if (isset($thisUser['extra'])) {
 				foreach ($thisUser['extra'] as $thisExtra) {
 					$eCount[$thisExtra]++;
 				}
			}
		}
	}

 	$conf_id = intval($conf_id);
 	$wHdl =& $xoopsDB->query("SELECT *  FROM " . $xoopsDB->prefix("confreg_extras") .
 	                         " WHERE ((conf_id=" . $conf_id . ")" .
 	                         " AND (start_date = '" . $starttime . "')" .
 	                         " AND (start_date <> end_date)" .
 	                         " AND (full <> 1))");

 	while ($aWorkshop = $xoopsDB->fetchArray($wHdl)) {
 		$eid = intval($aWorkshop['extra_id']);
 		// fetch number of reservations stored in database
 		$rHdl =& $xoopsDB->query("SELECT COUNT(*) as rcount" . 
 		                         " FROM " . $xoopsDB->prefix("confreg_extra_reservations") . 
 		                         " WHERE (extra_id = '" . $eid . "')");
 		$result = $xoopsDB->fetchArray($rHdl);
 		$count = intval($result['rcount']);
		// add reservations held for current users
 		if (!empty($eCount[$eid])) {
 			$count += intval($eCount[$eid]);
 		}
 
 		if ($count < intval($aWorkshop['max_attend'])) {
 			$aWorkshop['cur_res'] = $count;
 			$workshops[] = $aWorkshop;
 		}
 	}
	return $workshops;
}

/**
 * returns extras options that are still available
 * extras are options during registration offered with a checkbox
 *
 * @param integer $confid (conference id)
 * @param array $users => user data filled in so far
 * @return array of open extras
 */

function getExtras($conf_id, $users) {
	global $xoopsDB;

	// get counts for current user reservations not yet in database
	// loop through each user
	if (isset($users)) { 
 		foreach ($users as $thisUser) {
 			// loop through each extra reservation
 			if (isset($thisUser['extra'])) {
 				foreach ($thisUser['extra'] as $thisExtra) {
 					$eCount[$thisExtra]++;
 				}
			}
		}
	}

 	$conf_id = intval($conf_id);
 	$wHdl =& $xoopsDB->query("SELECT *  FROM " . $xoopsDB->prefix("confreg_extras") .
 	                         " WHERE ((conf_id=" . $conf_id . ")" .
 	                         " AND (start_date = end_date)" .
 	                         " AND (full <> 1))");

 	while ($aExtra = $xoopsDB->fetchArray($wHdl)) {
 		$eid = intval($aExtra['extra_id']);
		$max = intval($aExtra['max_attend']);
		
		if ($max == 0) {
			$aExtra['cur_res'] = 0;
			$extras[] = $aExtra;
			continue;
		}

 		// fetch number of reservations stored in database
		$rHdl =& $xoopsDB->query("SELECT COUNT(*) as rcount" . 
		                         " FROM " . $xoopsDB->prefix("confreg_extra_reservations") . 
	    	                     " WHERE (extra_id = '" . $eid . "')");
 		$result = $xoopsDB->fetchArray($rHdl);
		$count = intval($result['rcount']);
		// add reservations held for current users
 		if (!empty($eCount[$eid])) {
			$count += intval($eCount[$eid]);
		}

		if ($count < $max) {
			$aExtra['cur_res'] = $count;
			$extras[] = $aExtra;
 		}
 	}
	return $extras;
}

/**
 * returns an array of extras names
 *
 * @param integer $confid (conference id)
 * @return array of extras names
 */

function getExtraNames($conf_id) {
	global $xoopsDB;

 	$conf_id = intval($conf_id);
 	$wHdl =& $xoopsDB->query("SELECT *  FROM " . $xoopsDB->prefix("confreg_extras") .
 	                         " WHERE (conf_id=" . $conf_id . ")");

 	while ($aExtra = $xoopsDB->fetchArray($wHdl)) {
 		$e_id = intval($aExtra['extra_id']);
		$extras[$e_id] = $aExtra['name'];
	}
	return $extras;
}

/**
 * returns an array of extras dates
 *
 * @param integer $confid (conference id)
 * @return array of extras names
 */

function getExtraDates($conf_id) {
	global $xoopsDB;

 	$conf_id = intval($conf_id);
 	$request =& $xoopsDB->query("SELECT *  FROM " . $xoopsDB->prefix("confreg_extras") .
 	                         " WHERE (conf_id=" . $conf_id . ")");

 	while ($aExtra = $xoopsDB->fetchArray($request)) {
 		$e_id = intval($aExtra['extra_id']);
		$extras[$e_id] = strftime('%a %b %e, %Y', strtotime($aExtra['start_date']));
	}
	return $extras;
}

function getWorkshopNames($conf_id) {
	global $xoopsDB;

 	$conf_id = intval($conf_id);
 	$wHdl =& $xoopsDB->query('SELECT *  FROM ' . $xoopsDB->prefix("confreg_extras") .
 	                         ' WHERE (conf_id=' . $conf_id . ')' .
						 	 ' AND (start_date <> end_date)' .
						 	 ' ORDER BY start_date');

 	while ($aExtra = $xoopsDB->fetchArray($wHdl)) {
 		$e_id = intval($aExtra['extra_id']);
		$extras[$e_id] = $aExtra['name'];
	}
	return $extras;
}




/**
 * e-mails a confirmation message
 *
 * @param array $inputArr has all the company/user data
 * @param array $confData has all the conference information
 */

function mailConfirmation($confData, $group, $users) {
//	global $xoopsConfig;

	$to = $group['confirm_email'];
	$subject = $confData['title'] . " Registration Confirmation";
	$headers = 'From: registration@tmcmcmc.org' . "\r\n" .
				'Reply-To: registration@tmcmcmc.org' . "\r\n" .
				'Bcc: tmcmcmc@gmail.com' . "\r\n" .
				'X-Mailer: PHP/' . phpversion();

	$message = 'Thank you for registering for the ' . $confData['title'] . 
 				'. This is your confirmation of registration, not a confirmation of payment.' . "\n" .
  				"\n" .
				'If you need to mail a check for your payment, the address is:' . "\n" .
				str_ireplace('<br />', "\n",  _MD_CONFREG_ADDRESS) . "\n" .
				_MD_CONFREG_TAX_ID . "\n" .
				"\n" .
				"Billing Information" . "\n" .
				str_repeat('=', 40) . "\n" .
				"Confirmation: " . $group['confirmation'] . "\n" .
				"     Company: " . $group['company'] . "\n" .
				"Billing Name: " . $group['bill_fname'] . ' ' . $group['bill_lname'] . "\n" .
				"       Phone: " . $group['phone'] . "\n" .
				"  Pay Method: " . $group['paytype'] . "\n" .
				"     Address: " . $group['billaddress1'] . "\n" .
				"        City: " . $group['billcity'] . "\n" .
				"       State: " . $group['billstate'] . "\n" .
				"         Zip: " . $group['billzip'] . "\n" .
				"  Total Cost: " . $group['total_cost_disp'] . "\n" .
				"\n" . "Attendee Information" . "\n" .
				str_repeat('=', 40) . "\n";

	$total_count = count($users);
	foreach ($users as $thisUser) {
		$days_desc = trim(str_ireplace('<br />','; ',$thisUser['attend_desc']));
		$extra_desc = trim(str_ireplace('<br />','; ',$thisUser['extras_desc']));
		$message .= "\n     Attendee: " . $thisUser['user_id']+1 . " of ". $total_count ."\n" .
					"         Name: " . $thisUser['first_name'] . ' ' . $thisUser['last_name'] . "\n" .
					"       E-Mail: " . $thisUser['email'] . "\n" .
					"   TMC Number: " . $thisUser['member_num'] . "\n" .
					"         Days: " . $days_desc . "\n" .
					"Extra Options: " . $extra_desc . "\n" .
					"         Cost: " . $thisUser['cost_disp'] . "\n" .
					str_repeat("=",40) . "\n\n";
	}

	return mail($to, $subject, $message, $headers);

}

?>
